/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import java.io.File;
import java.net.URL;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import negocio.GestorAppMovilLocal;

/**
 *
 * @author Ing. Monica Merlo, Ing. Agustin  Fernandez
 */
public class AppMovilBean {

    @EJB(beanName = "GestorAppMovilBean")
    private GestorAppMovilLocal gestorAppMovilBean;

    /** Creates a new instance of AppMovilBean */
    public AppMovilBean() {
    }

    public String generarJarAppCelular() {
        URL url = this.getClass().getResource("/configuracion/SiGeoJ2ME.jar");
        File fJar = new File(url.getFile());
        url = getClass().getResource("/configuracion/SiGeoJ2ME.jad");
        File fJad = new File(url.getFile());
        url = getClass().getResource("/configuracion/MANIFEST.MF");
        File fMani = new File(url.getFile());
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

        File fDestino = new File(servletContext.getRealPath("/descarga/SiGeoJ2ME.jar"));

        LogueoBean logueoBean = (LogueoBean) context.getELContext().getELResolver().getValue(context.getELContext(), null, "LogueoBean");
        String puerto = String.valueOf(request.getServerPort());
        if (puerto != null) {
            if (!puerto.equals("0")) {
                puerto = ":" + request.getServerPort();
            } else {
                puerto = "";
            }
        } else {
            puerto = "";
        }
        String urlJar = "http://" + request.getServerName() + puerto + servletContext.getContextPath() + "/descarga/" + logueoBean.getUsuario() + "/";

        gestorAppMovilBean.generarJarParaDescarga(fJar, fJad, fMani, fDestino, urlJar, logueoBean.getUsuario(), logueoBean.getClave());

        return null;
    }

    public String eliminarDirectorioUsuario() {
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();

        File fDestino = new File(servletContext.getRealPath("/descarga/SiGeoJ2ME.jar"));

        LogueoBean logueoBean = (LogueoBean) context.getELContext().getELResolver().getValue(context.getELContext(), null, "LogueoBean");

        File fileDestinoUsuario = new File(fDestino.getParent() + File.separator + logueoBean.getUsuario(), "SiGeoJ2ME.jar");
        File dirUsuario = new File(fileDestinoUsuario.getParent());
        gestorAppMovilBean.eliminarDirectorioUsuario(dirUsuario);
        return null;
    }
}
